package com.lxl.cfca;


import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.lib.crypto.Session;
import cfca.sadk.lib.crypto.bcsoft.BCSoftLib;
import cfca.sadk.util.Base64;
import cfca.sadk.util.HashUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.digest.SM3;

/**
 * 验证 hutool工具类和 cfca 工具类下 加密 sm3 sha256 md5 值是否一样
 */
public class EncryptDemo {
    public static void main(String[] args) throws Exception {
        String plainText = "TESTING";
        // sha256加密
        sha256(plainText);
        // sm3加密
        sm3(plainText);
        // sm3加密
        md5(plainText);
    }

    private static void sha256(String content) throws Exception {
        // cfca sha256

        byte[] hash = HashUtil.RSAHashData(content.getBytes("UTF8"), new
                Mechanism(Mechanism.SHA256), BCSoftLib.INSTANCE(), false);
        //System.err.println(String.format("%40s: %102s", "demoSHA256HashMessage", TextHexKit.encode(hash)));
        System.out.println("cfca sha256 原始值 " + content + "  == Message:" + TextHexKit.encode(hash));
        // hutool sha256
        String sha256 = new Digester(DigestAlgorithm.SHA256).digestHex(content, "UTF-8");
        System.out.println("hutool sha256 原始值 " + content + "  == Message:" + sha256);
    }

    private static void sm3(String content) throws Exception {
        SM3 sm3 = new SM3();
        final String deviceName = JCrypto.JSOFT_LIB;
        JCrypto.getInstance().initialize(deviceName, null);
        final Session session = JCrypto.getInstance().openSession(deviceName);

        byte[] sourceData = content.getBytes("UTF8");
        byte[] data = HashUtil.SM3HashDataWithoutZValue(sourceData, session);
        //System.out.println("sm3 hash:" + new String(Base64.encode(data)));
        System.out.println("cfca sm3 原始值 " + content + "  == Message:" + new String(Base64.encode(data)));
        System.out.println("cfca sm3 原始值 " + content + "  == Message 16 进制:" + TextHexKit.encode(data));
        // hutool sm3
        String sha256 = sm3.digestHex(content);
        byte[] digest = sm3.digest(content);
        System.out.println("hutool sm3 原始值 " + content + "  == Message:" + sha256);
        System.out.println("hutool sm3 原始值 " + content + "  == Message1:" + new String(Base64.encode(digest)));
    }

    private static void md5(String content) throws Exception {
        // cfca md5
        byte[] hash = HashUtil.RSAHashData(content.getBytes("UTF8"), new
                Mechanism(Mechanism.MD5), BCSoftLib.INSTANCE(), false);
        System.out.println("cfca md5 原始值 " + content + "  == Message:" + TextHexKit.encode(hash));
        // hutool md5
        String md5 = new Digester(DigestAlgorithm.MD5).digestHex(content, "UTF-8");
        System.out.println("hutool md5 原始值 " + content + "  == Message:" + md5);
    }
}
